using System.Text;
using System.Text.Json;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

public class OcrClient(string baseUrl)
{
    private readonly HttpClient _httpClient = new HttpClient();
    private readonly string _baseUrl = baseUrl;

    // 修改方法签名，接收 Base64 字符串
    public async Task<(bool success, Dictionary<string, object>? result, string message)> SendOcrRequest(string base64Image)
    {
        var url = $"{_baseUrl}/ocr";

        // 移除可能存在的前缀（如 "data:image/jpeg;base64,"）
        if (base64Image.StartsWith("data:"))
        {
            int commaIndex = base64Image.IndexOf(',');
            if (commaIndex > 0)
            {
                base64Image = base64Image.Substring(commaIndex + 1);
            }
        }

        // 创建请求对象，与服务端模型匹配
        var data = new { image_data = base64Image };
        var jsonData = JsonSerializer.Serialize(data);
        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            var responseContent = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<Dictionary<string, object>>(responseContent);
            return (true, result, "");
        }
        catch (HttpRequestException e)
        {
            return (false, null, e.Message);
        }
        catch (JsonException e)
        {
            return (false, null, $"JSON 解析错误: {e.Message}");
        }
        catch (Exception e)
        {
            return (false, null, $"发生未知错误: {e.Message}");
        }
    }

    public static async Task<Image<Rgba32>> BytesToImage(Byte[] bytes)
    {
        var ms = new MemoryStream(bytes);
        var screenshot = await Image.LoadAsync<Rgba32>(ms);

        return screenshot;
    }

    public static async Task<string> ImageToBase64(Image<Rgba32> img)
    {
        using var ms = new MemoryStream();
        await img.SaveAsPngAsync(ms);
        var imgBytes = ms.ToArray();
        var resual = $"data:image/png;base64,{Convert.ToBase64String(imgBytes)}";

        return await Task.FromResult(resual);
    }

}